package com.maimao.core.utils;

import com.alibaba.fastjson.JSON;
import com.maimao.core.constant.Constants;
import com.maimao.core.model.auth.AuthUser;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author MaoLin Wang
 * @date 2020/12/2 2:54 下午
 */
public class Oauth2Util {
    public static AuthUser getUserFromRequest(HttpServletRequest request) {
        Map<String, Object> jwtClaims = getJwtClaimsFromHeader(request);
        String id = null;

        if (jwtClaims == null || (id = (String) jwtClaims.get(Constants.ID)) == null) {
            return null;
        }
        AuthUser authUser = new AuthUser();
        authUser.setId(id);
        Object shopId = jwtClaims.get(Constants.SHOP_ID);
        authUser.setShopId(Long.valueOf(String.valueOf(shopId==null?0:shopId)));
        authUser.setAvatar((String) jwtClaims.get(Constants.AVATAR));
        authUser.setType((String) jwtClaims.get(Constants.TYPE));
        authUser.setUsername((String) jwtClaims.get(Constants.USERNAME));
        authUser.setRealName((String)jwtClaims.get(Constants.REAL_NAME));
        authUser.setRole((String) jwtClaims.get("role"));
        return authUser;
    }

    public static Map<String, Object> getJwtClaimsFromJwt(String jwt) {
        if (StringUtils.isEmpty(jwt)) {
            return null;
        }
        Jwt decode = JwtHelper.decode(jwt);
        //得到 jwt中的用户信息
        String claims = decode.getClaims();
        //将jwt转为Map
        return JSON.parseObject(claims, Map.class);

    }

    public static Map<String, Object> getJwtClaimsFromHeader(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        //取出头信息
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization) || authorization.indexOf("Bearer") < 0) {
            return null;
        }
        //去掉Bearer  后的token信息
        String token = authorization.substring(7);
        Map<String, Object> map = null;
        try {
            //解析jwt
            map = getJwtClaimsFromJwt(token);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
